/**  
 * 缓存数据优化  
 * const storage = require('@/utils/storage');  
 * import storage from '@/utils/storage'  
 * 使用方法 【  
 *     一、设置缓存  
 *         string    storage.set('k', 'string你好啊');  
 *         json      storage.set('k', { "b": "3" }, 2);  
 *         array     storage.set('k', [1, 2, 3]);  
 *         boolean   storage.set('k', true);  
 *     二、读取缓存  
 *         默认值    storage.get('k')  
 *         string    storage.get('k', '你好')  
 *         json      storage.get('k', { "a": "1" })  
 *     三、移除/清理    
 *         移除: storage.remove('k');  
 *         清理：storage.clear();   
 * 】  
 * @type {String}  
 */

const postfix: string = '_expiry' // 缓存有效期后缀

/**  
  * 设置缓存   
  * @param  {[type]} key [键名]  
  * @param  {[type]} value [键值]  
  * @param  {[type]} time [时间、单位秒]  
*/
const set = (key: string, value: any, time?: string): void => {
  uni.setStorageSync(key, value)
  const seconds = parseInt(time)
  if (seconds > 0) {
    let timestamp: number = Date.parse(new Date().toDateString())
    timestamp = timestamp / 1000 + seconds
    uni.setStorageSync(key + postfix, timestamp + '')
  } else {
    uni.removeStorageSync(key + postfix)
  }
}

/**  
 * 获取缓存   
 * @param  {[type]} key   [键名]  
 * @param  {[type]} def [获取为空时\有效期超时的默认返回值]  
 */
const get = (key: string, def?: any): any => {
  const deadtime = parseInt(uni.getStorageSync(key + postfix))
  if (deadtime) {
    if (deadtime < Date.parse(new Date().toDateString()) / 1000) {
      if (def) {
        return def
      } else {
        return false
      }
    }
  }
  const res = uni.getStorageSync(key)
  if (res) {
    return res
  }
  if (def == undefined || def == "") {
    def = false
  }
  return def
}

/**
 * 删除指定缓存
 * @param {Object} key
 */
const remove = (key: string): void => {
  uni.removeStorageSync(key)
  uni.removeStorageSync(key + postfix)
}

/**  
 * 清理所有缓存  
 * @return {[type]} [description]  
 */
const clear = (): void => {
  uni.clearStorageSync()
}
export const useStorage = () => {
  return {
    set,
    get,
    remove,
    clear
  }
}